package com.lblin.method.area;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import com.lblin.method.enums.MethodEnum;

public class MethodUseArea {
	
	/**
	 * 方法枚举类：方法所在类的对象
	 */
	private Map<MethodEnum,Object> useLink = new HashMap<MethodEnum,Object>();
	
	private Map<MethodEnum,Method> useMethod = new HashMap<MethodEnum,Method>();

	public Map<MethodEnum,Object> getUseLink() {
		return useLink;
	}
	
	/**
	 * 获取方法所在的类的对象
	 * @param en
	 * @return
	 */
	public Object getMethodClass(MethodEnum en) {
		Object obj = getUseLink().get(en);
		try {
			if(obj==null) {//开始懒加载
				synchronized(useLink) {
					if(obj==null) {
						Class<?> clazz = Class.forName(en.getTarget());
						obj = clazz.newInstance();
						getUseLink().put(en, obj);
					}
				}
			}
		}catch (Exception e) {
			e.printStackTrace();
		}
		return obj;
	}
	
	public Method getMethod(MethodEnum en) {
		Method method = getUseMethod().get(en);
		try {
			if(method==null) {//开始懒加载
				synchronized(useMethod) {
					if(method==null) {
						Method[] methods = getMethodClass(en).getClass().getDeclaredMethods();
						for(Method m:methods) {
							if(m.getName().equals(en.getMethod())) {//类已经匹配
								m.setAccessible(true);
								method = m;
								break;
							}
						}
					}
				}
			}
		}catch (Exception e) {
			e.printStackTrace();
		}
		return method;
		
	}

	public void setUseLink(Map<MethodEnum,Object> useLink) {
		this.useLink = useLink;
	}

	public Map<MethodEnum,Method> getUseMethod() {
		return useMethod;
	}

	public void setUseMethod(Map<MethodEnum,Method> useMethod) {
		this.useMethod = useMethod;
	}
	

}
